package meijuli.com.join51.business.aliyun;

import android.content.ContentResolver;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.UUID;

import meijuli.com.join51.business.app.MApplication;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;

import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.utils.LogUtils;
import meijuli.com.join51.business.utils.StringUtil;
import retrofit2.Call;

/**
 * 作者:Ryan
 * 描述:阿里云OSS文件上传、下载工具类
 *
 * @author jack
 */
public class AliyunOSS {
    private static AliyunOSS sOss;
    private static OSSClient oss;
    private static String bucketName = "jhx-img1";
    private UploadListener mListener;
    private String URL_IMAGE_DOMAIN = "http://jhx-img1.join51.com/";
    private String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
    private OSSAsyncTask mTask;
    private Call<HttpResponse<AliOSS>> mAliCall;

    public static AliyunOSS get() {
        if (sOss == null) {
            synchronized (AliyunOSS.class) {
                if (sOss == null) {
                    sOss = new AliyunOSS();
                }
            }
        }
        return sOss;
    }

    /**
     * 初始化OSSClient , 在上传之前，这个方法至少执行一次
     */
    public void init() {
        mAliCall = ApiManager.get().getApiService(ApiService.class).getOSS();
        HttpRequest.getRequest().start(mAliCall, new ResponseCallback<AliOSS>() {

            @Override
            public void onSuccess(String url, AliOSS data) {
                if(data != null) {
                    initOSS(data);
                }
            }
        });
    }

    private void initOSS(AliOSS data) {
        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(data.getAccessKeyId(),
                data.getAccessKeySecret(),
                data.getSecurityToken());
        //该配置类如果不设置，会有默认配置，具体可看该类
        ClientConfiguration conf = new ClientConfiguration();
        // 连接超时，默认15秒
        conf.setConnectionTimeout(15 * 1000);
        // socket超时，默认15秒
        conf.setSocketTimeout(15 * 1000);
        // 最大并发请求数，默认5个
        conf.setMaxConcurrentRequest(5);
        // 失败后最大重试次数，默认2次
        conf.setMaxErrorRetry(2);
        oss = new OSSClient(MApplication.Companion.get(), endpoint, credentialProvider);
    }

    /**
     * 上传文件到阿里云
     *
     * @param sourceFilePath 源文件的路径
     * @return 返回TaskHandler事件调度类，可以取消、暂停和继续下载任务
     */
    public void upload(final String sourceFilePath, final UploadListener listener) throws FileNotFoundException {
        mListener = listener;
        //获取东八区时间
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
        String year = calendar.get(Calendar.YEAR) + "";
        //获取月份，0表示1月份
        String month = calendar.get(Calendar.MONTH) + 1 + "";
        String day   = calendar.get(Calendar.DAY_OF_MONTH) + "";
        String objectKey = year + "/" + month + "/" + day + "/" + createUUID() + ".jpg";
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(bucketName, objectKey, sourceFilePath);
        if(oss != null) {
            mTask = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(final PutObjectRequest request, PutObjectResult result) {
                    LogUtils.d("PutObject", "UploadSuccess");
                    LogUtils.d("ETag", result.getETag());
                    LogUtils.d("RequestId", result.getRequestId());
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            mListener.onSuccess(URL_IMAGE_DOMAIN + request.getObjectKey(), sourceFilePath);
                        }
                    });
                }
                @Override
                public void onFailure(final PutObjectRequest request, final ClientException clientExcepion, ServiceException serviceException) {
                    // 请求异常
                    if (clientExcepion != null) {
                        // 本地异常如网络异常等
                        clientExcepion.printStackTrace();
                    }
                    if (serviceException != null) {
                        // 服务异常
                        LogUtils.e("ErrorCode", serviceException.getErrorCode());
                        LogUtils.e("RequestId", serviceException.getRequestId());
                        LogUtils.e("HostId", serviceException.getHostId());
                        LogUtils.e("RawMessage", serviceException.getRawMessage());
                    }
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            mListener.onFailure(URL_IMAGE_DOMAIN + request.getObjectKey(), clientExcepion);
                        }
                    });
                }
            });
        }
    }

    public String getAliyunImageUrl(String bucketName, String cloudKey) {
        if (StringUtil.isEmpty(bucketName) || StringUtil.isEmpty(cloudKey)) {
            return null;
        }
        return "http://www.aimianfei.com/" + bucketName + "_B_U_C_K_E_T_AND_K_E_Y_" + cloudKey;
    }

    /**
     * 根据文件路径，获取文件类型
     */
    private String getFileType(String filePath) {
        File f = new File(filePath);
        return getFileType(f);
    }

    /**
     * 根据文件获取文件类型
     */
    private String getFileType(File f) {
        if (f.exists()) {
            Uri uri = Uri.fromFile(f);
            ContentResolver cR = MApplication.Companion.get().getContentResolver();
            return cR.getType(uri) == null ? "" : cR.getType(uri);
        } else {
            return "";
        }
    }

    /**
     * 生成uuid作为图片的唯一标识
     * @return
     */
    private String createUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public void recycler() {
        if(mTask != null) {
            mTask.cancel();
        }
        if(mAliCall != null) {
            mAliCall.cancel();
        }
        mTask = null;
        mAliCall = null;
        mListener = null;
    }
}
